package com.zkdcloud.aspectInterceptor.advice;

import com.xdja.interceptor.advice.HttpAdvice;
import com.xdja.interceptor.exception.InvokeException;
import com.zkdcloud.domain.Admin;
import com.zkdcloud.util.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.zkdcloud.constant.Constants.HTTP_CONSTANTS.REQUEST_ADMIN;

/**
 * @author zk123
 * @version 2018/5/23
 */
@Component
public class TokenAdvice implements HttpAdvice{
    /**
     * token
     */
    public static String TOKEN_HEADER = "token";

    @Override
    public void doAdvice(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Map<String, Object> map) throws InvokeException {
        String tokenString = httpServletRequest.getHeader(TOKEN_HEADER);
        if(StringUtils.isEmpty(tokenString)){
            throw new InvokeException("请重新登录");
        }

        try {
            Admin admin = TokenUtil.getTokenAdmin(tokenString);
            map.put(REQUEST_ADMIN,admin);
            httpServletRequest.setAttribute(REQUEST_ADMIN,admin);
        } catch (Exception e) {
            throw new InvokeException("请重新登录");
        }
    }
}
